import 'package:cached_network_image/cached_network_image.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:lazy_food/models/degrease_model.dart';
import 'package:lazy_food/models/tab_model.dart';
import 'package:lazy_food/net/network.dart';
import 'package:lazy_food/util/string+.dart';
import 'package:scrollview_observer/scrollview_observer.dart';

class DegreasePage extends StatefulWidget {
  @override
  State<DegreasePage> createState() => _DegreasePageState();
}

class _DegreasePageState extends State<DegreasePage>
    with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  List<DegreaseModel> _models = [];
  List<TabModel> _tabs = [];
  EasyRefreshController _refreshController =
      EasyRefreshController(controlFinishRefresh: true);
  int _currentTab = 0;
  ScrollController _scrollController = ScrollController();
  late ListObserverController _listObserverController;

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _listObserverController =
        ListObserverController(controller: _scrollController);
  }

  void _getData() async {
    EasyLoading.show();
    List<Object> results =
        await Future.wait([_getDegrease(), _getDegreaseTabs()]);
    setState(() {
      _models = results[0] as List<DegreaseModel>;
      List<TabModel> tabs = results[1] as List<TabModel>;
      tabs.insert(0, TabModel('all', '全部'));
      _tabs = tabs;
    });
    EasyLoading.dismiss();
    _refreshController.finishRefresh();
  }

  Future<List<DegreaseModel>> _getDegrease() {
    return Network.getDegrease();
  }

  Future<List<TabModel>> _getDegreaseTabs() {
    return Network.getDegreaseTabs();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      backgroundColor: Colors.black,
      body: EasyRefresh(
        refreshOnStart: true,
        onRefresh: _getData,
        child: ListView.separated(
          itemCount: _models.length,
          scrollDirection: Axis.vertical,
          padding: EdgeInsets.only(left: 20, right: 20),
          itemBuilder: (context, index) {
            if (index == 0) {
              return Container(
                height: 88,
                child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      SizedBox(
                        height: 50,
                      ),
                      Text('饮食计划',
                          style: TextStyle(
                              color: Colors.white,
                              fontSize: 25,
                              fontWeight: FontWeight.bold)),
                    ]),
              );
            } else if (index == 1) {
              return Container(
                height: 64,
                padding: EdgeInsets.fromLTRB(0, 10, 0, 10),
                child: ListViewObserver(
                  controller: _listObserverController,
                  child: ListView.builder(
                    scrollDirection: Axis.horizontal,
                    itemCount: _tabs.length,
                    controller: _scrollController,
                    itemBuilder: (context, index) {
                      TabModel model = _tabs[index];
                      return GestureDetector(
                        child: Container(
                          padding: EdgeInsets.fromLTRB(20, 10, 20, 10),
                          margin: EdgeInsets.only(right: 10),
                          height: 44,
                          child: Text(
                            model.text,
                            style: TextStyle(color: Colors.black, fontSize: 16),
                          ),
                          decoration: BoxDecoration(
                              color: _currentTab == index
                                  ? Colors.white
                                  : Colors.white54,
                              borderRadius: BorderRadius.circular(22)),
                        ),
                        onTap: () {
                          print(index);
                          setState(() {
                            _currentTab = index;
                            _listObserverController.animateTo(
                              index: index,
                              duration: Duration(milliseconds: 100),
                              curve: Curves.ease,
                            );
                          });
                        },
                      );
                    },
                  ),
                ),
              );
            } else {
              DegreaseModel model = _models[index - 2];
              String number = '${model.n_join_users}'.dealNumber();
              if (model.n_tasks > 0) {
                number = '${model.n_tasks}天 · ' + number;
              }
              number += '人参加过';
              return Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    width: MediaQuery.of(context).size.width - 20,
                    height: MediaQuery.of(context).size.width - 20,
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(20),
                      child: CachedNetworkImage(
                        imageUrl: model.cover_image.url_pattern.toImage(),
                        placeholder: (context, s) {
                          return Image.asset('assets/images/placeholder.png');
                        },
                        height: MediaQuery.of(context).size.width - 20,
                        fit: BoxFit.cover,
                      ),
                    ),
                  ),
                  Divider(
                    height: 5,
                  ),
                  Text(
                    model.name,
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: 16,
                        fontWeight: FontWeight.bold),
                  ),
                  Text(
                    number,
                    style: TextStyle(color: Colors.white, fontSize: 14),
                  ),
                  SizedBox(
                    height: 5,
                  )
                ],
              );
            }
          },
          separatorBuilder: (context, index) {
            return Divider(
              height: 10,
            );
          },
        ),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}
